#!/usr/bin/perl
# cdn_upstream_high.pm
# Copyright (C) 2006, 2007  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information: http://carrierclass.net/
#
use CCNCore::Provisioning;
use CCNCore::Provision::Base;
use CCN::ssh;

# Retrieves $what files from the cdn servers.
# (This should be run on an aggregating server.)

sub run($$)
{
    my $what = shift;
    my $compressed = shift;
    my $p = new CCNCore::Provisioning;
    my $b = new CCNCore::Provision::Base($p);

    mkdir CCNCore::Home::config."/cdn";
    mkdir CCNCore::Home::config."/cdn/$what";
    my $base = CCNCore::Home::config."/cdn/$what/system";
    mkdir $base;

    $p->sql_do_for( <<'SQL',
        SELECT DISTINCT cdn_upstream_server FROM server;
SQL
    sub
    {
        my $cdn_pk = shift;
        # Do not replicate if we are that server.
        next if $cdn_pk == $p->server_pk;
        my $cdn_ip = $b->primary_ip($cdn_pk);

        $p->sql_do_for( <<'SQL', $cdn_pk,
            SELECT pk FROM server WHERE cdn_upstream_server = ?
SQL
        sub
        {
            my $server_pk = shift;
            my $server_ip = $b->primary_ip($server_pk);
            mkdir "${base}/${server_ip}";
            system  q(rsync -e ').$CCN::ssh::command.q(' )
                   .qq("root\@${cdn_ip}:${base}/${server_ip}/")
                   .q( / ) == 0
            or $b->warn("cdn_upstream_high: rsync ${cdn_ip}:${base}/${server_ip}/ / failed: $!");
        });
    });
}

1;